package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageBean;
import com.zzyl.dto.UserDto;
import com.zzyl.entity.Dept;
import com.zzyl.entity.Post;
import com.zzyl.entity.User;
import com.zzyl.entity.UserRole;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.*;
import com.zzyl.properties.SecurityProperties;
import com.zzyl.service.DeptService;
import com.zzyl.service.UserService;
import com.zzyl.utils.NoProcessing;
import com.zzyl.utils.ThreadLocalUtil;
import com.zzyl.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 用户表服务实现类
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private SecurityProperties securityProperties;
    @Autowired
    private PostMapper postMapper;
    @Autowired
    private RoleMapper roleMapper;


    /**
     * 用户分页查询
     */
    @Override
    public PageBean<UserVo> pageQuery(Integer pageNum, Integer pageSize, UserDto dto) {
        PageHelper.startPage(pageNum,pageSize);

        String s = NoProcessing.processString(dto.getDeptNo());
        dto.setDeptNo(s);
        Page<UserVo> page = userMapper.getPage(dto);
        return PageBean.of(page,UserVo.class);
    }

    /**
     * 用户添加
     * @param dto
     */
    @Override
    @Transactional
    public void add(UserDto dto) {

        //转换UserVo为User
        User user = BeanUtil.toBean(dto, User.class);

        user.setUsername(user.getEmail());
        user.setNickName(user.getRealName());
        user.setDataState("0");//0正常 1停用
        //TODO 需要设置默认，并且需要加密
        String password = DigestUtil.bcrypt(securityProperties.getDefaultPassword());
        user.setPassword(password);

        userMapper.insert(user);


        Set<String> roleVoIds = dto.getRoleVoIds();

        List<UserRole> list = new ArrayList<>();
        for (String roleId : roleVoIds) {
            UserRole userRole = new UserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId(Long.valueOf(roleId));
            userRole.setDataState("0");
            list.add(userRole);
        }
        userRoleMapper.batchInsert(list);
    }

    @Override
    @Transactional
    public void updateUser(UserDto userDto) {
        //根据部门编号查询，是否是最底层的部门，如果不是，不允许添加用户
        int count = deptMapper.isLowestDept(userDto.getDeptNo());
        if (count > 0) {
            throw new BaseException(BasicEnum.USER_LOCATED_BOTTOMED_DEPT);
        }

        //转换UserVo为User
        User user = BeanUtil.toBean(userDto, User.class);
        user.setUsername(userDto.getEmail());
        userMapper.updateByPrimaryKeySelective(user);

        if (CollUtil.isEmpty(userDto.getRoleVoIds())) {
            return;
        }

        //删除角色中间表
        userRoleMapper.deleteUserRoleByUserId(user.getId());
        //重新保存角色中间表
        userDto.getRoleVoIds().forEach(roleId -> {
            UserRole userRole = UserRole.builder()
                    .userId(user.getId())
                    .roleId(Long.valueOf(roleId))
                    .dataState("0")
                    .build();
            userRoleMapper.insert(userRole);
        });
    }

    @Override
    @Transactional
    public void deleteUserById(Long userId) {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 删除用户与岗位关联
        userMapper.deleteByPrimaryKey(userId);
    }

    /**
     * 启用或禁用用户
     */
    @Override
    public void enableOrDisable(Long id, String status) {
        User user = User.builder()
                .id(id)
                .dataState(status)
                .build();
        userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public List<UserVo> list(UserDto dto) {
        List<User> userList = userMapper.selectList();
        return BeanUtil.copyToList(userList, UserVo.class);
    }

    @Override
    public void updatePasswords(Long userId) {
        String password = DigestUtil.bcrypt(securityProperties.getDefaultPassword());
        User user = User.builder()
                .password(password)
                .id(userId)
                .build();
        userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public UserVo getById() {

        Long userId = ThreadLocalUtil.get();

        User user = userMapper.selectByPrimaryKey(userId);
        UserVo userVo = BeanUtil.toBean(user, UserVo.class);

        Dept dept = deptMapper.selectByDeptNo(userVo.getDeptNo());
        Post post = postMapper.selectByPostNo(userVo.getPostNo());

        userVo.setDeptName(dept.getDeptName());
        userVo.setPostName(post.getPostName());

        List<Long> list = userRoleMapper.selectByUserId(userVo.getId());

        Set<String> set = new HashSet<>();
        for (Long aLong : list) {
            String roleName = roleMapper.selectByPrimaryKey(aLong).getRoleName();
            set.add(roleName);
//            set.add(aLong.toString());
        }
        userVo.setRoleNames(set);
        return userVo;
    }


}

